package com.example.fyptest3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.R.integer;
import android.os.Bundle;
import android.os.Environment;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class AlbumActivity extends Activity implements View.OnClickListener{
	private final int ALBUM_DEFAULT_SIZE = 180;
	private File[] array_album_folders = new File [1000];
	private int i_ALBUM = 0;
	static private Button[] button_albums;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_album);
		
		//change title text to
		setTitle("<< Photo menu");
		
		//change title bar color to CYAN
		ActionBar bar = getActionBar();
		bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00C4CD")));
		
		//change title bar text to WHITE
		int actionBarTitleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
		if (actionBarTitleId >0){
			TextView title = (TextView)findViewById(actionBarTitleId);
			if (title != null){
				title.setTextColor(Color.WHITE);
			}
		}
		
		//find proper folders with images
		locateAllFoldersThatCanBeAlbums();
		
		//create albums
		createAlbums();
		
		for(int i=0; i<button_albums.length; i++){
			button_albums[i].setOnClickListener(this);
			button_albums[i].setId(i);
		}
		
		
	}

	//action bar menus functionality implemented
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle presses on the action bar items
	    switch (item.getItemId()) {
	        case R.id.menu_assign:
	        	Intent myIntent = new Intent(AlbumActivity.this, AssignmentActivity.class);
	    		startActivity(myIntent);				
	            return true;
	        case R.id.menu_settings:
	            //openSettings();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_album, menu);
		//return true;
		return super.onCreateOptionsMenu(menu);
	}
	
	
	//MU FUNCTIONS/////////////////////////////////////////////////////////////////
	//LOCATE ALL FILES IN ALL FOLDERS IN STORAGE DEVICE------------------------
	private void locateAllFoldersThatCanBeAlbums(){
		
		File sdcard = Environment.getExternalStorageDirectory(); //root path
		File dirs = new File(sdcard.getAbsolutePath());	
		int i=0;
		try {
			checkDirForImages(dirs, i);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//-------------------------------------------------------------------------
	
	
	//GET ALL FILES OF DIRECTORY--------------------------------------------------------------------
	private void checkDirForImages(File directory, int i) throws IOException { // /mnt/sdcard , 0
		
		boolean sameDir = false;
		final File[] files = directory.listFiles();
		if(files != null){
			for(File file : files){
				if(file != null){
					if(file.isDirectory()){  // it is a folder...
						if(i+1<3){
							checkDirForImages(file, i+1);
						}else{
							break;
						}
					}
					else {  // it is a file...
						if(!sameDir){
							if(isImage(file)){
								sameDir = true;
								String ss = file.getParentFile().getAbsolutePath().toString();
								if(!ss.contains(".")){
									array_album_folders[i_ALBUM++] = file.getParentFile();	
								}
							}
						}
					}
				}
			}	
		}
	}
	//--------------------------------------------------------------------------------------------------
	
	
	//CHECK IF FILE IS IMAGE------------------------------------------
	public boolean isImage(File file) {
	    if (file == null || !file.exists()) {
	        return false;
	    }
	    BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    BitmapFactory.decodeFile(file.getPath(), options);
	    return options.outWidth != -1 && options.outHeight != -1;
	}
	//----------------------------------------------------------------
	
	
	//CREATE ALBUM FOLDERS as BUTTONS-----------------------------------------------------------
	public void createAlbums(){
		TableLayout tbLayout02 = (TableLayout)findViewById(R.id.tableLayout02);
			
			int nAlbums = i_ALBUM;
			Display display = getWindowManager().getDefaultDisplay();
			int nAlbumsPerRow = display.getWidth()/ALBUM_DEFAULT_SIZE; //3
			int nR = nAlbums%nAlbumsPerRow; //1
			int nRows = nAlbums/nAlbumsPerRow; //2
			if(nR!=0)nRows++;//3
			
			button_albums = new Button[nAlbums];
			TextView[] tv_albums = new TextView[nAlbums];
			TableRow[] tablerow02 = new TableRow[nRows*2];
			LinearLayout[] linearlayout02 = new LinearLayout[nRows*2];
			
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ALBUM_DEFAULT_SIZE, ALBUM_DEFAULT_SIZE);
			LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(ALBUM_DEFAULT_SIZE-50, 20);
			layoutParams.setMargins(10,5,0,-5);
			layoutParams2.setMargins(10,0, 50,0);
			
			int k=0;
			for(int i=0; i<nRows; i++){	//0-2
				tablerow02[i+k] = new TableRow(this); //0,2,
				linearlayout02[i+k] = new LinearLayout(this); //0,2
				tablerow02[i+k+1] = new TableRow(this); //1,3
				linearlayout02[i+k+1] = new LinearLayout(this); //1,3
				for(int j=0; j<nAlbumsPerRow; j++){
					if(i*nAlbumsPerRow+j < nAlbums){
					button_albums[i*nAlbumsPerRow+j] = new Button(this); //0-2, 3-5, 6-8
					tv_albums[i*nAlbumsPerRow+j] = new TextView(this);
					button_albums[i*nAlbumsPerRow+j].setLayoutParams(layoutParams);
					tv_albums[i*nAlbumsPerRow+j].setLayoutParams(layoutParams2);
					tv_albums[i*nAlbumsPerRow+j].setText(array_album_folders[i*nAlbumsPerRow+j].getName().toString());
					tv_albums[i*nAlbumsPerRow+j].setTextColor(Color.WHITE);
					//tv_albums[i*nAlbumsPerRow+j].setBackgroundColor(Color.parseColor("#ffffff"));
					tv_albums[i*nAlbumsPerRow+j].setGravity(Gravity.CENTER);
					//tv_albums[i*nAlbumsPerRow+j].setBackgroundResource(R.drawable.tags_rounded_corners);
					linearlayout02[i+k].addView(button_albums[i*nAlbumsPerRow+j]);
					linearlayout02[i+k+1].addView(tv_albums[i*nAlbumsPerRow+j]);
					button_albums[i*nAlbumsPerRow+j].setBackgroundDrawable(drawCanvasForAlbum(array_album_folders[i*nAlbumsPerRow+j].getAbsolutePath().toString()));		
					}
				}
				tablerow02[i+k].addView(linearlayout02[i+k]);
				tablerow02[i+k+1].addView(linearlayout02[i+k+1]);
				tbLayout02.addView(tablerow02[i+k]);
				tbLayout02.addView(tablerow02[i+k+1]);
				k++;
				
			}
			

	}
	//------------------------------------------------------------------------------------------------------

	
	//DRAW CANVAS the COVER for ALBUM----------------------------------------------------------
	public Drawable drawCanvasForAlbum(String path){
	
		File f = new File(path);        
		File file[] = f.listFiles();
		
		File f2 = new File(Environment.getExternalStorageDirectory().toString()+"/dcim/celeb");        
		File file2[] = f2.listFiles();
	
		Bitmap[] bm = new Bitmap[6];
		bm[0] = ImageDecode.staticDecodeFile(file2[0]);
		if(isImage(file[0])){
			bm[0] = ImageDecode.staticDecodeFile(file[0]);			
		}

		
		int countImagesInFile = 0;
		for(int i=0; i<file.length; i++){
			if(isImage(file[i])){
				countImagesInFile++;
			}
		}
		
		if(countImagesInFile>=6){
			int k=0;
			for(int i=0; i<file.length; i++){
				if(isImage(file[i])){
					if(k>=6)
						break;
					else{
						bm[k] = ImageDecode.staticDecodeFile(file[i]);
						k++;
					}
				}
			}
			
		}else if(countImagesInFile==5){
			int k=0;
			int j1=0;
			for(int i=0; i<file.length; i++){
				if(isImage(file[i])){
					if(k>=5)
						break;
					else{
						if(k==0)
							j1=i;
						bm[k] = ImageDecode.staticDecodeFile(file[i]);
						k++;
					}
				}
			}
			bm[5] = ImageDecode.staticDecodeFile(file[j1]);
		}else if(countImagesInFile==4){
			int k=0;
			int j1=0, j2=0;
			for(int i=0; i<file.length; i++){
				if(isImage(file[i])){
					if(k>=4)
						break;
					else{
						if(k==0)
							j1=i;
						if(k==1)
							j2=i;
						bm[k] = ImageDecode.staticDecodeFile(file[i]);
						k++;
					}
				}
			}
			bm[4] = ImageDecode.staticDecodeFile(file[j1]);
			bm[5] = ImageDecode.staticDecodeFile(file[j2]);
		}else if(countImagesInFile==3){
			int k=0;
			int j1=0, j2=0, j3=0;
			for(int i=0; i<file.length; i++){
				if(isImage(file[i])){
					if(k>=3)
						break;
					else{
						if(k==0)
							j1=i;
						if(k==1)
							j2=i;
						if(k==2)
							j3=i;
						bm[k] = ImageDecode.staticDecodeFile(file[i]);
						k++;
					}
				}
			}
			bm[3] = ImageDecode.staticDecodeFile(file[j1]);
			bm[4] = ImageDecode.staticDecodeFile(file[j2]);
			bm[5] = ImageDecode.staticDecodeFile(file[j3]);
		}else if(countImagesInFile==2){
			int k=0;
			int j1=0, j2=0;
			for(int i=0; i<file.length; i++){
				if(isImage(file[i])){
					if(k>=2)
						break;
					else{
						if(k==0)
							j1=i;
						if(k==1)
							j2=i;
						bm[k] = ImageDecode.staticDecodeFile(file[i]);
						k++;
					}
				}
			}
			bm[2] = ImageDecode.staticDecodeFile(file[j1]);
			bm[3] = ImageDecode.staticDecodeFile(file[j2]);
			bm[4] = ImageDecode.staticDecodeFile(file[j1]);
			bm[5] = ImageDecode.staticDecodeFile(file[j2]);
		}else if(countImagesInFile==1){
			int k=0;
			int j1=0;
			for(int i=0; i<file.length; i++){
				if(isImage(file[i])){
					if(k>=1)
						break;
					else{
						if(k==0)
							j1=i;
						bm[k] = ImageDecode.staticDecodeFile(file[i]);
						k++;
					}
				}
			}
			bm[1] = ImageDecode.staticDecodeFile(file[j1]);
			bm[2] = ImageDecode.staticDecodeFile(file2[0]);
			bm[3] = ImageDecode.staticDecodeFile(file[j1]);
			bm[4] = ImageDecode.staticDecodeFile(file2[0]);
			bm[5] = ImageDecode.staticDecodeFile(file[j1]);
		}
					
			
		Bitmap bitmap_album = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
		Canvas canvas_album = new Canvas(bitmap_album);
	
		bm[0] = Bitmap.createScaledBitmap(bm[0], 150, 150, true);
		bm[1] = Bitmap.createScaledBitmap(bm[1], 150, 150, true);
		bm[2] = Bitmap.createScaledBitmap(bm[2], 150, 150, true);
		bm[3] = Bitmap.createScaledBitmap(bm[3], 150, 150, true);
		bm[4] = Bitmap.createScaledBitmap(bm[4], 150, 150, true);
		bm[5] = Bitmap.createScaledBitmap(bm[5], 150, 150, true);
	
		canvas_album.drawBitmap(bm[0],50,0,null);
		canvas_album.drawBitmap(bm[1],40,10,null);
		canvas_album.drawBitmap(bm[2],30,20,null);
		canvas_album.drawBitmap(bm[3],20,30,null);
		canvas_album.drawBitmap(bm[4],10,40,null);
		canvas_album.drawBitmap(bm[5],0,50,null);
	
		BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap_album);
	
		return drawable;
		
	}
	
	//open album when album icon clicked, function for all albums
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent myIntent = new Intent(AlbumActivity.this, InsideAlbumActivity.class);
		myIntent.putExtra("album_dir", array_album_folders[v.getId()].toString());
		startActivity(myIntent);				
	}

//END	
}
